package com.example.myapplication.socket;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class LocalSocketStart extends Thread {
    private final String TAG = "ServerThread";
    private ServerSocket serverSocket;
    private boolean isServerRuning = false; //服务器是否在运行
    public Map<String, SocketThread> socketThreadMap = new HashMap<>(); //客户端列表  ip:端口，客户端
    private int port = 0;
    private Handler handler = null;
    private String sendData = null;

    public LocalSocketStart(int port) {
        this.handler = handler;
        this.port = port;
    }



    public void start() {
        try {
            serverSocket = new ServerSocket(port);
            isServerRuning = true;
            super.start();
            Log.e(TAG, "本地服务器运行成功");
        } catch (IOException e) {
            e.printStackTrace();
            isServerRuning = false;
            Log.e(TAG, "服务器运行失败");
        }
    }

    @Override
    public void interrupt() {
        isServerRuning = false;
        if (socketThreadMap != null) {
            Log.e(TAG, "连接本地客户端个数：" + socketThreadMap.size());
            Iterator<String> iterator = socketThreadMap.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                socketThreadMap.get(key).interrupt();
            }
            socketThreadMap.clear();
            socketThreadMap = null;
        }
        Log.e(TAG, "连接本地客户端资源释放完毕");
        //关闭服务器
        if (serverSocket != null) {
            try {
                serverSocket.close();
                serverSocket = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.e(TAG, "关闭本地服务器完毕");
        super.interrupt();
    }

    //获取服务器是否在运行
    public boolean isServerRuning() {
        return isServerRuning;
    }

    @Override
    public void run() {
        super.run();
        while (isServerRuning()) {
            try {
                Socket socket = serverSocket.accept(); //等待客户端连接
                Log.e(TAG, "连接本地客户端连接上：" + socket.toString());
                if (socket != null) {
                    Log.d(TAG, "run: " + "来了老弟");
                    SocketThread socketThread = new SocketThread(socket);
                    socketThread.start();

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void sendMsg(String sendData) {
        this.sendData = sendData;

    }

    //客户端线程
    public  class SocketThread extends Thread {
        Socket socket;
        InputStream inputStream;
        String key = "";
        String sendData = "";
        public SocketThread(Socket socket) {
            key = socket.getInetAddress() + ":" + socket.getPort();
            this.socket = socket;
        }

        @Override
        public void interrupt() {
            if (socket != null) {
                try {
                    socket.close();
                    socket = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                    inputStream = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                this.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            super.interrupt();
        }

        @Override
        public void run() {
            while (true){
                Log.d("我要发向客户端的数据是", "run: " + sendData);
                try {
                    OutputStream outputStream = socket.getOutputStream();
                    outputStream.write(sendData.getBytes(StandardCharsets.UTF_8));
                    outputStream.flush();
                } catch (Exception e) {
                    Log.e(TAG, "本地Server: Error");
                    e.printStackTrace();
                } finally {
                    this.interrupt();
                    Log.e(TAG, "本地Server: Close:");
                }
            }
        }
    }
}
